package configurationReader;

import com.configurator.FieldData;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Sawior
 */
public class SpacesReader {

    public static Map<Integer, FieldData> loadSpacesFile() {
        Map<Integer, FieldData> dest = new HashMap<>();
        try {
            Document doc = readConfigFile();
            readSpace(doc.getElementsByTagName("space"), dest);
        } catch (IOException | ParserConfigurationException | DOMException | SAXException e) {
            Logger.getLogger(SpacesReader.class.getName()).log(Level.SEVERE, "[CarPark] Cannot load config file", e);
        }
        return dest;
    }

    private static Document readConfigFile() throws SAXException, ParserConfigurationException, IOException {
        File fXmlFile = new File(".\\src\\main\\resources\\configSpaces.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        return doc;
    }

    private static void readSpace(NodeList nList, Map<Integer, FieldData> dest) throws DOMException {
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                Integer number = Integer.parseInt(eElement.getElementsByTagName("number").item(0).getTextContent());
                String type = eElement.getElementsByTagName("type").item(0).getTextContent();
                String status = eElement.getElementsByTagName("status").item(0).getTextContent();
                Integer column = Integer.parseInt(eElement.getElementsByTagName("column").item(0).getTextContent());
                Integer row = Integer.parseInt(eElement.getElementsByTagName("row").item(0).getTextContent());
                Integer level = Integer.parseInt(eElement.getElementsByTagName("level").item(0).getTextContent());
                dest.put(temp, new FieldData("Stanowisko", number, type, status, column, row, level));
            }
        }
    }

}
